package com.xs.ahoi.hcxs.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.xs.ahoi.hcxs.Ahoi;
import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.dao.BookDao;
import com.xs.ahoi.hcxs.dao.ConfigDao;
import com.xs.ahoi.hcxs.handler.NotifyPlayHandler;
import com.xs.ahoi.hcxs.listener.TtsListener;
import com.xs.ahoi.hcxs.model.Book;
import com.xs.ahoi.hcxs.service.BGMService;
import com.xs.ahoi.hcxs.service.BookFactory;
import com.xs.ahoi.hcxs.service.FloatWinsService;
import com.xs.ahoi.hcxs.ui.dialog.*;
import com.xs.ahoi.hcxs.ui.view.BookContentView;
import com.xs.ahoi.hcxs.utils.*;
import com.xs.ahoi.hcxs.utils.tts.TtsUtil;

import java.util.Optional;

import static com.xs.ahoi.hcxs.utils.Constants.DEFAULT_CHARSET;
import static com.xs.ahoi.hcxs.utils.Constants.ERROR_LOG_NAME;


/**
 * 阅读页面activity
 *
 * @author: fuhuichao
 * @date: 2021/9/16 5:01 下午
 */
public class BookContentActivity extends BaseActivity {

    @BindView(R.id.vBookContent)
    public BookContentView contentView;
    //    @BindView(R.id.tvTts)
//    public TextView tvTts;
    @BindView(R.id.ivTts)
    public ImageView ivTts;
    @BindView(R.id.ivTimer)
    public ImageView ivTimer;
    @BindView(R.id.tvTimer)
    public TextView tvTimer;
    @BindView(R.id.bottomMenu)
    public LinearLayout bottomMenu;
    @BindView(R.id.layoutTopArea)
    public RelativeLayout layoutTopArea;
    @BindView(R.id.tvBookName)
    public TextView tvBookName;
    @BindView(R.id.tvSelectedBtns)
    public LinearLayout tvSelectedBtns;
    @BindView(R.id.layoutMore)
    public RelativeLayout layoutMore;

    // 背景音乐控制器
    private BGMService.BGMBinder bgmControl = Ahoi.getInstance().getBGMControl();

    // 颜色选择弹框
    private ColorPickerDialog colorPickerDialog;
    private BookFactory bookFactory;
    // 文字当前页的canvas
    private Canvas canvasCurPage, canvasNextPage;
    // 文字当前页的位图
    private Bitmap bitmapCurPage, bitmapNextPage;
    // 屏幕尺寸
    private int screenWidth, screenHeight;
    // 电量系统manager
    private BatteryManager batteryManager;
    // 剪贴板
    private ClipboardManager clipboardManager;
    // 标记是否显示菜单 false: 隐藏，true：显示
    private boolean menuShowing = false;
    // 标记播放或者暂停 false: 未播放，true：正在播放
    private boolean isPlay = false;
    // 播放按钮图标, 暂停按钮图标
    private Drawable drawablePlay, drawablePause;
    // 定时按钮图片
    private Drawable drawableTimer, drawableTimerActive;
    // 菜单的动画
    private Animation animBottomMenuShow, animBottomMenuHide;
    // 选中文字后弹出框的动画
    private Animation animSelectBtnsShow;
    private int bookId;
    private Book book;

    // 阅读页面设置弹窗
    private DialogSetting dialogSetting;
    // 进度弹窗
    private DialogPercent dialogPercent;
    // 点击更多时的气泡弹窗
    private DialogContentMore dialogContentMore;
    // loading弹窗
    private DialogLoading dialogLoading;
    // 选中后替换的弹窗
    private DialogReplace dialogReplace;
    // 分享弹框
    private DialogShare dialogShare;
    // 通用提示弹框
    private DialogCommonTips dialogCommonTips;

    // 选中文字后的弹出框
    private RelativeLayout.LayoutParams selectBtnParam;

    // 悬浮窗intent
    private Intent floatWinsIntent;

    // 工具类
    private ConfigDao configDao;
    private BookDao bookDao;

    //region ********************DialogListener  监听**************************

    // VIEW触摸事件监听
    private BookContentView.ContentTouchListener touchListener = new BookContentView.ContentTouchListener() {
        @Override
        public Boolean prevPage() {
            if (bookFactory.isPageFirst()) {
                ToastUtil.show(R.string.first_page);
                return false;
            } else {
                doPagePrev();
                return true;
            }
        }

        @Override
        public Boolean nextPage(Integer position) {
            if (bookFactory.isPageLast()) {
                ToastUtil.show(R.string.last_page);
                return false;
            } else {
                doPageNext(position);
                return true;
            }
        }

        @Override
        public void refreshPage() {
            refreshView();
        }

        @Override
        public Boolean isPlaying() {
            return isPlay;
        }

        @Override
        public void showMenu() {
            BookContentActivity.this.showMenu();
        }

        @Override
        public void cancel() {
            bookFactory.cancelPage();
        }

        @Override
        public Boolean checkMenuShow() {
            if (menuShowing) {
                BookContentActivity.this.hideMenu();
                return true;
            }
            return false;
        }

        @Override
        public void stopPlay(boolean isActStop) {
            BookContentActivity.this.stopPlay(isActStop);
        }

        @Override
        public void cancelTimer() {
            setTimerBtnBg();
        }

        @Override
        public Boolean startPlay() {
            return BookContentActivity.this.startPlay();
        }

        @Override
        public void showSelectedBtns(float positionY) {
            showSelectBtns(positionY);
        }

        @Override
        public void hideSelectedBtns() {
            hideSelectBtns();
        }
    };

    // 设置页面事件监听
    private DialogSetting.SettingListener settingListener = new DialogSetting.SettingListener() {
        @Override
        public void changeLight(int progress) {
            configDao.setLight(progress);
            LightUtil.setLight(BookContentActivity.this, progress);
        }

        @Override
        public void changeRowSpacing(int progress) {
            bookFactory.changeRowSpacing(progress + Constants.DEFAULT_ROW_SPACING_DIFF);
            doPageNext(bookFactory.getMbbIndexStart());
        }

        @Override
        public float changeTextSize(Constants.ChangeType type) {
            float textSize = bookFactory.changeTextSize(type);
            if (textSize > -1) {
                doPageNext(bookFactory.getMbbIndexStart());
            }
            return textSize;
        }

        @Override
        public void changeCharset(String charset) {
            configDao.setCharset(book.getPath(), charset);
            doPageNext(bookFactory.getMbbIndexStart());
        }

        @Override
        public void changePageStyle(int pageStyle) {
            configDao.setPageStyle(pageStyle);
            contentView.setPageStyle(pageStyle);
        }

        @Override
        public void changeBackground(int index, String bgColor, String textColor, String titleColor) {
            configDao.setBackgroundIndex(index);
            // 设置页面背景和文字颜色
            bookFactory.setBgColor(Color.parseColor(bgColor));
            bookFactory.setTextColor(Color.parseColor(textColor));
            bookFactory.setTitleColor(Color.parseColor(titleColor));
            doPageNext(bookFactory.getMbbIndexStart());
        }
    };

    // TTS阅读事件监听器
    private TtsListener ttsListener = new TtsListener() {
        @Override
        public void refreshPage() {
            doPageNext(bookFactory.getMbbIndexStart(), false);
        }

        @Override
        public void nextPage() {
            doPageNext(null);
        }

        @Override
        public Boolean isPlaying() {
            return isPlay;
        }
    };

    // 进度监听
    private DialogPercent.DialogPercentListener percentListener = this::doPageNext;

    // 替换弹窗
    private DialogReplace.ReplaceListener replaceListener = new DialogReplace.ReplaceListener() {
        @Override
        public void showLoading(String text) {
            dialogLoading.show(text);
        }

        @Override
        public void hideLoading() {
            dialogLoading.dismiss();
        }
    };

    // 分享弹窗
    private DialogShare.ShareListener shareListener = intent -> {
        startActivity(intent);
    };

    // 右上角更多弹窗
    private DialogContentMore.ContentMoreListener contentMoreListener = new DialogContentMore.ContentMoreListener() {
        @Override
        public void hideMenu() {
            BookContentActivity.this.hideMenu();
        }

        @Override
        public void openReplace() {
            bookFactory.stopPlay(true);
            dialogReplace.setOldText("");
            showReplaceDialog();
        }

        @Override
        public void openSearch() {
            Intent intent = new Intent(BookContentActivity.this, BookSearchActivity.class);
            startActivityForResult(intent, Constants.REQUEST_CODE_ACTIVITY);
            hideMenu();
        }
    };

    //endregion **********************************************************

    //region ********************初始化**************************

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 获取书架页面传递的书籍ID
        bookId = intent.getIntExtra(Constants.DEFAULT_ID, 0);

        // 获取上次播放的bookId，如果不相等，说明打开了一本新的书，则停止播放
        int oldBookId = configDao.getBookId();
        if (oldBookId != -1 && bookId != oldBookId) {
            reInit();
        } else {
            // 如果打开的是error.log文件，则每次都刷新
            String path = Optional.ofNullable(bookDao.getById(bookId)).map(Book::getPath).orElse(null);
            if (path != null && path.contains(ERROR_LOG_NAME)) {
                reInit();
            }
        }
        afterInit();

        // 刷新页面，主要目的是重新获取偏好设置
        bookFactory.init();
        doPageNext(bookFactory.getMbbIndexStart(), false);
    }

    private void reInit() {
        bookFactory.stopPlay(true);
        TtsUtil.getInstance().reset();
        init();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.hideStatusBar();
        setContentView(R.layout.activity_book_content);
        ButterKnife.bind(this);

        // 获取书架页面传递的书籍ID
        bookId = getIntent().getIntExtra(Constants.DEFAULT_ID, 0);
        init();
    }

    private void afterInit() {
        // 设置屏幕亮度
        if (configDao.getIsSystemLight()) {
            int light = LightUtil.setSystemLight((Ahoi.getInstance().getActivity()));
            configDao.setLight(light);
        } else {
            LightUtil.setLight(this, configDao.getLight());
        }
    }

    private void init() {
        configDao = ConfigDao.getInstance();
        bookDao = BookDao.getInstance();

        // 缓存本次打开的bookId
        configDao.setBookId(bookId);

        // 背景灯常亮
        if (configDao.getIsAlwaysLight()) {
            LightUtil.keepScreenAlwaysLight(this);
        }

        // 获取书籍对象
        book = bookDao.getById(bookId);
        tvBookName.setText(book.getName());

        // 播放和暂停的图标
        drawablePlay = ContextCompat.getDrawable(this, R.drawable.icon_play);
        drawablePause = ContextCompat.getDrawable(this, R.drawable.icon_pause);
        // 定时按钮图标
        drawableTimer = ContextCompat.getDrawable(this, R.drawable.icon_timer);
        drawableTimerActive = ContextCompat.getDrawable(this, R.drawable.icon_timer_active);

        // 设置默认的播放按钮图片
        setTtsBtnBg();

        // 菜单的动画
        animBottomMenuShow = AnimationUtils.loadAnimation(this, R.anim.content_bottom_menu_show);
        animBottomMenuHide = AnimationUtils.loadAnimation(this, R.anim.content_bottom_menu_hide);

        // 选中文字后弹出框的动画
        animSelectBtnsShow = AnimationUtils.loadAnimation(this, R.anim.content_select_btns_show);

        // 获取手机电量
        batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);

        // 获取剪贴板
        clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

        // 获取屏幕尺寸
        screenWidth = MeasureUtil.getScreenWidth(this);
        screenHeight = MeasureUtil.getScreenHeight(this);

        // 创建位图，初始化canvas
        bitmapCurPage = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
        bitmapNextPage = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
        canvasCurPage = new Canvas(bitmapCurPage);
        canvasNextPage = new Canvas(bitmapNextPage);

        // 获取bookFactory
        bookFactory = BookFactory.getInstance().open(bookId).size(screenWidth, screenHeight).init();
        bookFactory.setContentView(contentView);

        // 传递view初始化参数
        contentView.setBitmap(bitmapCurPage, bitmapNextPage);
        contentView.setSize(screenWidth, screenHeight);
        contentView.setTouchListener(touchListener);
        contentView.setPageStyle(configDao.getPageStyle());
        contentView.init();

        // 设置选中文字后的弹出框
        selectBtnParam = new RelativeLayout.LayoutParams(tvSelectedBtns.getLayoutParams());
        selectBtnParam.addRule(RelativeLayout.CENTER_HORIZONTAL);
        selectBtnParam.leftMargin = selectBtnParam.rightMargin = 40;

        // 设置TTS监听
        TtsUtil.getInstance().setTtsListener(ttsListener);

        // 画一页内容
        doPageNext(null, false);

        // 初始化进度弹窗
        dialogPercent = new DialogPercent(this, bookId);
        dialogPercent.setDialogPercentListener(percentListener);

        // 初始化右上角更多弹窗
        dialogContentMore = new DialogContentMore(this);
        dialogContentMore.setListener(contentMoreListener);

        // 初始化设置弹窗
        dialogSetting = new DialogSetting(this, book.getPath());
        dialogSetting.setSettingListener(settingListener);

        // 初始化loading弹窗
        dialogLoading = new DialogLoading(this, getString(R.string.replace_ing));
        dialogLoading.setOnDismissListener(dialogInterface -> Constants.canReplace = false);

        // 选中后替换的弹窗
        dialogReplace = new DialogReplace(this);
        dialogReplace.setListener(replaceListener);

        // 分享弹框
        dialogShare = new DialogShare(this);
        dialogShare.setShareListener(shareListener);

        // 通用的提示弹框
        dialogCommonTips = new DialogCommonTips(this);

        // 悬浮窗intent
        floatWinsIntent = new Intent(this, FloatWinsService.class);

    }

    //endregion **********************************************

    @OnClick({R.id.btnTts, R.id.btnCatalog, R.id.btnSetting, R.id.btnPercent, R.id.btnTimer,
            R.id.arrowLeft, R.id.layoutMore, R.id.tvCopy, R.id.tvReplace,
            R.id.tvSearchThis, R.id.tvShare, R.id.tvPlay})
    public void onClick(View v) {
        switch (v.getId()) {
            // 播放/暂停
            case R.id.btnTts:
                if (isPlay) {
                    bookFactory.stopPlay(true);
                } else {
                    bookFactory.startPlay();
                }
                break;
            // 目录
            case R.id.btnCatalog:
                Intent intent = new Intent(this, BookCatalogActivity.class);
                intent.putExtra(Constants.BOOK_ID, bookId);
                startActivityForResult(intent, Constants.REQUEST_CODE_ACTIVITY);
                hideMenu();
                break;
            // 设置
            case R.id.btnSetting:
                hideMenu();
                dialogSetting.show();
                break;
//            // 自定义背景颜色
//            case R.id.tvBgSelfDifined:
//                colorPickerDialog = new ColorPickerDialog(
//                        this,
//                        tvTextSizeNumber.getTextColors().getDefaultColor(),
//                        getResources().getString(R.string.app_name),
//                        tvTextSizeNumber::setTextColor);
//                colorPickerDialog
//                        .setWindowSize(screenWidth, screenHeight)
//                        .show();
//                break;
            // 进度
            case R.id.btnPercent:
                hideMenu();
                dialogPercent.show();
                break;
            // 定时
            case R.id.btnTimer:
                startActivity(new Intent(BookContentActivity.this, BookTimerActivity.class));
                break;
            // 返回箭头
            case R.id.arrowLeft:
                hideMenu();
                this.onBackPressed();
                break;
            // 更多，弹出全文搜索和加入书签
            case R.id.layoutMore:
                dialogContentMore.setClickedView(layoutMore);
                dialogContentMore.show();
                break;
            // 长按弹出-复制
            case R.id.tvCopy:
                selectCopy();
                break;
            // 长按弹出-替换
            case R.id.tvReplace:
                selectReplace();
                break;
            // 长按弹出-分享
            case R.id.tvShare:
                share();
                break;
            // 长按弹出-播放
            case R.id.tvPlay:
                selectToPlay();
                break;
            // 长按弹出-全文搜索
            case R.id.tvSearchThis:
                gotoSearch();
                break;
            default:
                break;
        }
    }

    // 长按弹出-复制
    private void selectCopy() {
        String charSelected = bookFactory.getPageCharSelected();
        clipboardManager.setPrimaryClip(ClipData.newPlainText("text", charSelected));
        ToastUtil.show(getString(R.string.copySuccess));

        // 取消长按事件
        contentView.finishLongPress();

        // 关闭长按弹出框
        hideSelectBtns();
        doPageNext(bookFactory.getMbbIndexStart());
    }

    // 长按弹出-替换
    private void selectReplace() {

        // 取消长按事件
        contentView.finishLongPress();

        // 弹出替换弹窗
        String charSelected = bookFactory.getPageCharSelected();
        dialogReplace.setOldText(charSelected);
        showReplaceDialog();

        // 关闭长按弹出框
        hideSelectBtns();
        doPageNext(bookFactory.getMbbIndexStart());
    }

    // 长按弹出-分享
    private void share() {

        // 取消长按事件
        contentView.finishLongPress();

        // 弹出分享弹窗
        String charSelected = bookFactory.getPageCharSelected();
        dialogShare.setShareType(Constants.ShareType.text);
        dialogShare.setTextContent(charSelected);
        dialogShare.show();

        // 关闭长按弹出框
        hideSelectBtns();
        doPageNext(bookFactory.getMbbIndexStart());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_CODE_ACTIVITY) {
            switch (resultCode) {
                // 从目录页面或搜索页面跳转过来
                case Constants.RESULT_CODE_CATALOG_OR_SEARCH:
                    // 获取书籍目录下标
                    int position = data.getExtras().getInt(Constants.POSITION);
                    doPageNext(position);
                    break;
                default:
                    break;
            }
        }
    }

    // 向前翻一页
    private void doPagePrev() {
        bookFactory.cleanPageCharDatas();
        bookFactory.saveTempPageVo();
        bookFactory.setPowerPercent(getPowerPercent());
        bookFactory.doDraw(canvasCurPage);
        bookFactory.pagePrev();
        bookFactory.doDraw(canvasNextPage);
        TtsUtil.getInstance().reset();
        if (isPlay) {
            TtsUtil.getInstance().start();
        }
        // 更新通知栏
        NotifyPlayHandler.getInstance().pushNotify();
    }

    // 向后翻一页
    private void doPageNext(Integer mbbIndex) {
        doPageNext(mbbIndex, true);
    }

    // 向后翻一页
    private void doPageNext(Integer mbbIndex, boolean resetTTS) {
        try {
            bookFactory.cleanPageCharDatas();
            bookFactory.saveTempPageVo();
            bookFactory.setPowerPercent(getPowerPercent());
            if (!isPlay) {
                bookFactory.doDraw(canvasCurPage);
            }
            bookFactory.pageNext(mbbIndex);
            bookFactory.doDraw(canvasNextPage);
            if (resetTTS) {
                TtsUtil.getInstance().reset();
                // 最后一页，不继续
                if (bookFactory.isPageLast()) {
                    bookFactory.stopPlay(true);
                    return;
                }
                if (isPlay) {
                    TtsUtil.getInstance().start();
                }
            }
            // 更新通知栏
            NotifyPlayHandler.getInstance().pushNotify();
        } catch (Exception e) {
            LogUtil.e("doPageNext Exception: " + e.getMessage(), e);
        }
    }

    // 设置播放/暂停
    private void setTtsBtnBg() {
        if (isPlay) {
            ivTts.setImageDrawable(drawablePause);
        } else {
            ivTts.setImageDrawable(drawablePlay);
        }
    }

    // 显示菜单
    private void showMenu() {
        menuShowing = true;
        layoutTopArea.setVisibility(View.VISIBLE);
        bottomMenu.setVisibility(View.VISIBLE);
        bottomMenu.startAnimation(animBottomMenuShow);
    }

    // 隐藏菜单
    private void hideMenu() {
        menuShowing = false;
        layoutTopArea.setVisibility(View.GONE);
        bottomMenu.setVisibility(View.GONE);
        bottomMenu.startAnimation(animBottomMenuHide);
    }

    // 显示藏长按选中弹出框
    private void showSelectBtns(float positionY) {
        selectBtnParam.topMargin = (int) positionY;
        tvSelectedBtns.setLayoutParams(selectBtnParam);
        tvSelectedBtns.setVisibility(View.VISIBLE);
        tvSelectedBtns.startAnimation(animSelectBtnsShow);
    }

    // 隐藏长按选中弹出框
    private void hideSelectBtns() {
        tvSelectedBtns.setVisibility(View.GONE);
    }

    // 停止阅读 isActStop:是否真正停止，并丢失焦点
    private void stopPlay(boolean isActStop) {
        isPlay = false;
        if (isActStop) {
            TtsUtil.getInstance().stop();
        } else {
            TtsUtil.getInstance().pause();
        }
        // 暂停bgm
        stopBGM();
        setTtsBtnBg();
        // 更新通知栏
        NotifyPlayHandler.getInstance().pushNotify();
        // 停止悬浮窗
        stopFloatWinsService(floatWinsIntent);
        if (isActStop) {
            Ahoi.throwAuditFocus();
        }
    }

    // 开始阅读
    private Boolean startPlay() {
        try {
            isPlay = true;
            if (TtsUtil.getInstance().start()) {
//            Ahoi.getAuditFocus();
                // 播放bgm
                startBGM();
                // 取消长按事件
                contentView.finishLongPress();
                setTtsBtnBg();
                // 更新通知栏
                NotifyPlayHandler.getInstance().pushNotify();
                // 启动悬浮窗
                startFloatWinsService(floatWinsIntent);
                return true;
            } else {
                ToastUtil.show("未知原因，播放失败~");
                return false;
            }
        } catch (Exception e) {
            LogUtil.e("播放失败: " + e.getMessage());
            return false;
        }
    }

    private void startBGM() {
        if (bgmControl == null) {
            bgmControl = Ahoi.getInstance().getBGMControl();
        }
        if (bgmControl != null) {
            bgmControl.start();
        }
    }

    private void stopBGM() {
        if (bgmControl != null) {
            bgmControl.pause();
        }
    }

    // 阅读指定文字
    private void selectToPlay() {

        // 获取长按文字
        String charSelected = bookFactory.getPageCharSelected();
        TtsUtil.getInstance().speakText(charSelected);
    }

    // 跳转到搜索页面
    private void gotoSearch() {
        Intent intent = new Intent(BookContentActivity.this, BookSearchActivity.class);
        intent.putExtra("searchText", bookFactory.getPageCharSelected());
        startActivityForResult(intent, Constants.REQUEST_CODE_ACTIVITY);

        // 取消长按事件
        contentView.finishLongPress();

        // 关闭长按弹出框
        hideSelectBtns();
    }

    // 获取手机电量百分比数值
    private int getPowerPercent() {
        return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    }

    // 刷新当前页面
    private void refreshView() {
        bookFactory.refresh(canvasCurPage, canvasNextPage);
    }

    // 设置定时按钮样式
    private void setTimerBtnBg() {
        if (TimerDownUtil.getInstance().getLeaveSecond() > -1) {
            ivTimer.setImageDrawable(drawableTimerActive);
            tvTimer.setTextColor(ContextCompat.getColor(this, R.color.colorRed));
        } else {
            ivTimer.setImageDrawable(drawableTimer);
            tvTimer.setTextColor(ContextCompat.getColor(this, R.color.colorWhite));
        }
    }

    // 打开查找替换弹框
    private void showReplaceDialog() {
        if (!configDao.getCharset(book.getPath()).equals(DEFAULT_CHARSET)) {
            dialogCommonTips.setListener(() -> {
                boolean b = FileUtil.convertToUTF8(book.getPath());
                if (b) {
                    ToastUtil.show("转码成功！");
                } else {
                    ToastUtil.show("转码失败！");
                }
            });
            dialogCommonTips.show("当前编码不是UTF-8，是否转换？");
        } else {
            dialogReplace.show();
        }
    }

    @Override
    protected void onPause() {
        bookFactory.updateLastPosition();
        super.onPause();
    }

    @Override
    protected void onResume() {
        configDao.setOpenContentActivity(true);
        setTimerBtnBg();
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        if (contentView.isLongPressRun()) {
            contentView.finishLongPress();
            hideSelectBtns();
            contentView.postInvalidate();
        } else if (menuShowing) {
            hideMenu();
        } else {
            configDao.setOpenContentActivity(false);
            Intent intent = new Intent(BookContentActivity.this, IndexActivity.class);
            intent.putExtra("back", "1");
            startActivity(intent);
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        }
    }
}
